package org.aynu.orderservice.controller;

import lombok.extern.slf4j.Slf4j;
import org.aynu.orderservice.common.OrderConstants;
import org.aynu.orderservice.common.OrderResponse;
import org.aynu.orderservice.entity.OrderEntity;
import org.aynu.orderservice.entity.OrderItemsEntity;
import org.aynu.orderservice.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 订单控制器
 *
 * @author 小粥
 * @since 2025/03/03
 */
@Slf4j
@RestController
@RequestMapping("/order")
@Validated
public class OrderController {

    private final OrderService orderService;

    @Autowired
    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 从 Map 中安全获取 Integer 参数
     *
     * @param map 参数映射
     * @param key 键名
     * @return Integer 或 null（如果键不存在）
     * @throws IllegalArgumentException 如果参数格式错误
     */
    private Integer getIntegerParam(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return null;
        }
        try {
            return Integer.parseInt(value.toString());
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(key + " 参数格式错误，必须为整数");
        }
    }

    /**
     * 从 Map 中安全获取 BigDecimal 参数
     *
     * @param map 参数映射
     * @param key 键名
     * @return BigDecimal
     * @throws IllegalArgumentException 如果参数为空或格式错误
     */
    private BigDecimal getBigDecimalParam(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            throw new IllegalArgumentException(key + " 参数不能为空");
        }
        try {
            return new BigDecimal(value.toString());
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(key + " 参数格式错误，必须为数字");
        }
    }

    private Object[] buildOrderAndItems(Map<String, Object> map) {
        OrderEntity order = new OrderEntity();
        Integer userId = getIntegerParam(map, "userId");
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID（userId）必须提供且大于0");
        }
        order.setUserId(userId);
        order.setStatus(OrderConstants.STATUS_WAIT_PAY);

        Integer cartId = getIntegerParam(map, "cartId");

        Object itemsObj = map.get("items");
        if (!(itemsObj instanceof List)) {
            throw new IllegalArgumentException("订单项列表（items）必须是一个列表");
        }

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> itemsList = (List<Map<String, Object>>) itemsObj;
        if (itemsList.isEmpty()) {
            throw new IllegalArgumentException("订单项列表（items）不能为空");
        }

        List<OrderItemsEntity> orderItems = new ArrayList<>();
        for (Map<String, Object> itemMap : itemsList) {
            OrderItemsEntity item = new OrderItemsEntity();
            Integer productId = getIntegerParam(itemMap, "productId");
            Integer quantity = getIntegerParam(itemMap, "quantity");
            if (productId == null || productId <= 0) {
                throw new IllegalArgumentException("商品ID（productId）必须提供且大于0");
            }
            if (quantity == null || quantity <= 0) {
                throw new IllegalArgumentException("购买数量（quantity）必须提供且大于0");
            }
            item.setProductId(productId);
            item.setQuantity(quantity);
            item.setUnitPrice(getBigDecimalParam(itemMap, "unitPrice"));
            orderItems.add(item);
        }

        return new Object[]{order, orderItems, cartId};
    }

    /**
     * 创建订单
     *
     * @param map 请求参数
     * @return OrderResponse<Integer>
     */
    @RequestMapping(value = "/createOrder", method = RequestMethod.POST)
    public OrderResponse<Integer> createOrder(@RequestBody Map<String, Object> map) {
        try {
            Object[] entities = buildOrderAndItems(map);
            OrderEntity order = (OrderEntity) entities[0];
            List<OrderItemsEntity> items = (List<OrderItemsEntity>) entities[1];
            Integer cartId = (Integer) entities[2];
            if (cartId == null || cartId <= 0) {
                throw new IllegalArgumentException("购物车ID（cartId）必须提供且大于0");
            }
            return orderService.createOrder(order, items, cartId);
        } catch (Exception e) {
            log.error("从购物车创建订单失败: params={}, error={}", map, e.getMessage(), e);
            return OrderResponse.error("创建订单失败: " + e.getMessage());
        }
    }

    /**
     * 直接创建订单
     *
     * @param map 请求参数
     * @return OrderResponse<Integer>
     */
    @RequestMapping(value = "/directCreateOrder", method = RequestMethod.POST)
    public OrderResponse<Integer> directCreateOrder(@RequestBody Map<String, Object> map) {
        try {
            Object[] entities = buildOrderAndItems(map);
            OrderEntity order = (OrderEntity) entities[0];
            List<OrderItemsEntity> items = (List<OrderItemsEntity>) entities[1];
            return orderService.directCreateOrder(order, items);
        } catch (Exception e) {
            log.error("直接创建订单失败: params={}, error={}", map, e.getMessage(), e);
            return OrderResponse.error("直接创建订单失败: " + e.getMessage());
        }
    }

    /**
     * 按用户 ID 选择订单
     *
     * @param map 请求参数
     * @return OrderResponse<List<Map<String, Object>>>
     */
    @RequestMapping(value = "/selectOrdersByUserId", method = RequestMethod.POST)
    public OrderResponse<List<Map<String, Object>>> selectOrdersByUserId(@RequestBody Map<String, Object> map) {
        try {
            Integer userId = getIntegerParam(map, "userId");
            if (userId == null || userId <= 0) {
                throw new IllegalArgumentException("用户ID（userId）必须提供且大于0");
            }
            return orderService.selectOrdersByUserId(userId);
        } catch (Exception e) {
            log.error("查询用户订单失败: params={}, error={}", map, e.getMessage(), e);
            return OrderResponse.error("查询用户订单失败: " + e.getMessage());
        }
    }

    /**
     * 选择 Order by ID （按 ID 排序）
     *
     * @param map 请求参数
     * @return OrderResponse<Map<String, Object>>
     */
    @RequestMapping(value = "/selectOrderById", method = RequestMethod.POST)
    public OrderResponse<Map<String, Object>> selectOrderById(@RequestBody Map<String, Object> map) {
        try {
            Integer orderId = getIntegerParam(map, "orderId");
            if (orderId == null || orderId <= 0) {
                throw new IllegalArgumentException("订单ID（orderId）必须提供且大于0");
            }
            return orderService.selectOrderById(orderId);
        } catch (Exception e) {
            log.error("查询订单详情失败: params={}, error={}", map, e.getMessage(), e);
            return OrderResponse.error("查询订单详情失败: " + e.getMessage());
        }
    }

    /**
     * 更新订单状态
     *
     * @param map 请求参数
     * @return OrderResponse<Integer>
     */
    @RequestMapping(value = "/updateOrderStatus", method = RequestMethod.POST)
    public OrderResponse<Integer> updateOrderStatus(@RequestBody Map<String, Object> map) {
        try {
            Integer orderId = getIntegerParam(map, "orderId");
            String status = Objects.toString(map.get("status"), null);
            if (orderId == null || orderId <= 0) {
                throw new IllegalArgumentException("订单ID（orderId）必须提供且大于0");
            }
            if (status == null) {
                throw new IllegalArgumentException("订单状态（status）不能为空");
            }
            return orderService.updateOrderStatus(orderId, status);
        } catch (Exception e) {
            log.error("更新订单状态失败: params={}, error={}", map, e.getMessage(), e);
            return OrderResponse.error("更新订单状态失败: " + e.getMessage());
        }
    }

    /**
     * 按用户取消订单
     *
     * @param map 请求参数
     * @return OrderResponse<Integer>
     */
    @RequestMapping(value = "/cancelOrderByUser", method = RequestMethod.POST)
    public OrderResponse<Integer> cancelOrderByUser(@RequestBody Map<String, Object> map) {
        try {
            Integer orderId = getIntegerParam(map, "orderId");
            Integer userId = getIntegerParam(map, "userId");
            if (orderId == null || orderId <= 0) {
                throw new IllegalArgumentException("订单ID（orderId）必须提供且大于0");
            }
            if (userId == null || userId <= 0) {
                throw new IllegalArgumentException("用户ID（userId）必须提供且大于0");
            }
            return orderService.cancelOrderByUser(orderId, userId);
        } catch (Exception e) {
            log.error("用户取消订单失败: params={}, error={}", map, e.getMessage(), e);
            return OrderResponse.error("用户取消订单失败: " + e.getMessage());
        }
    }

    /**
     * 按系统取消订单
     *
     * @param map 请求参数
     * @return OrderResponse<Integer>
     */
    @RequestMapping(value = "/cancelOrderBySystem", method = RequestMethod.POST)
    public OrderResponse<Integer> cancelOrderBySystem(@RequestBody Map<String, Object> map) {
        try {
            Integer orderId = getIntegerParam(map, "orderId");
            if (orderId == null || orderId <= 0) {
                throw new IllegalArgumentException("订单ID（orderId）必须提供且大于0");
            }
            return orderService.cancelOrderBySystem(orderId);
        } catch (Exception e) {
            log.error("系统取消订单失败: params={}, error={}", map, e.getMessage(), e);
            return OrderResponse.error("系统取消订单失败: " + e.getMessage());
        }
    }

    /**
     * 完成订单
     *
     * @param map 请求参数
     * @return OrderResponse<Integer>
     */
    @RequestMapping(value = "/completeOrder", method = RequestMethod.POST)
    public OrderResponse<Integer> completeOrder(@RequestBody Map<String, Object> map) {
        try {
            Integer orderId = getIntegerParam(map, "orderId");
            if (orderId == null || orderId <= 0) {
                throw new IllegalArgumentException("订单ID（orderId）必须提供且大于0");
            }
            return orderService.updateOrderStatus(orderId, OrderConstants.STATUS_COMPLETED);
        } catch (Exception e) {
            log.error("将订单标记为已完成失败: params={}, error={}", map, e.getMessage(), e);
            return OrderResponse.error("将订单标记为已完成失败: " + e.getMessage());
        }
    }
}